package com.freedom.monitor.myeye.metrics.server.pool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.freedom.monitor.myeye.metrics.server.task.StorageRunnable;
import com.freedom.monitor.myeye.metrics.server.utils.PropertyUtils;
import com.freedom.rpc.thrift.common.utils.Logger;

public class StorageExecutorPool {
	private static final Logger logger = Logger.getLogger(StorageExecutorPool.class);
	//
	private static String QUEUE_SIZE = "queueSize";
	private static String NETTY_WORKER = "nettyWorker";
	//
	private static ExecutorService EXECUTOR = null;
	private static LinkedBlockingQueue<Runnable> QUEUE = null;

	private StorageExecutorPool() {

	}

	static {
		// 1)队列
		int size = Integer.parseInt(PropertyUtils.getInstance().getProperty(QUEUE_SIZE));
		QUEUE = new LinkedBlockingQueue<Runnable>(size);
		// 2)业务线程数
		int cpu = Runtime.getRuntime().availableProcessors();
		int workerNum = cpu * Integer.parseInt(PropertyUtils.getInstance().getProperty(NETTY_WORKER));
		logger.info("workerNum Threads--->" + workerNum);
		// 下面一行跟Executors.newFixedThreadPool本质是一模一样的
		// 3)构造线程池
		EXECUTOR = new ThreadPoolExecutor(workerNum, workerNum, 0L, TimeUnit.MILLISECONDS, QUEUE);
	}

	public static void execute(String data) {
		try {// 如果队列满了,就会被丢弃,队列满了，说明后端存储出现问题:存储挂了,性能瓶颈等
			EXECUTOR.execute(new StorageRunnable(data));
		} catch (Exception e) {
			logger.error(e.toString());
		}
	}

}
